﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Siva.CBC.Barnacle.ashx
{
    /// <summary>
    /// ajHandler 的摘要说明
    /// </summary>
    public class ajHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;
            //context.Response.AppendHeader("Content-Encoding", "gzip"); // 关键压缩代码
            context.Response.BufferOutput = false; // 关键：禁用缓冲

            string sql = @"SELECT accountId, recordTime 
                       FROM aj 
                       WHERE recordTime >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)";
            
            try
            {
                using (var writer = new StreamWriter(context.Response.OutputStream))
                {
                    writer.Write("["); // 开始JSON数组

                    using (var connection = new MySqlConnection(SqlHelper.GetSqlConnectionString()))
                    using (var command = new MySqlCommand(sql, connection))
                    {
                        connection.Open();
                        using (var reader = command.ExecuteReader())
                        {
                            bool isFirstRow = true;
                            while (reader.Read())
                            {
                                if (!isFirstRow)
                                    writer.Write(",");
                                isFirstRow = false;

                                // 直接映射到JSON对象
                                string accountId = reader["accountId"].ToString(); // 作为字符串处理
                                DateTime recordTime = reader.GetDateTime(1);

                                writer.Write("{");
                                writer.Write(string.Format("\"accountId\":\"{0}\",",accountId));
                                writer.Write(string.Format("\"recordTime\":\"{0}\"",recordTime.ToString("yyyy-MM-dd")));
                                writer.Write("}");
                            }
                        }
                    }

                    writer.Write("]"); // 结束JSON数组
                }
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = 500;
                context.Response.Write(string.Format("{{\"error\":\"{0}\"}}",ex.Message));
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}